<template>
<div class="cart">
    <HeaderCart><span slot="back" class="back" @click="goback" >返回</span>
    <span slot="home" class="home" @click="gohome">首页</span></HeaderCart>
    <div class="cart-list" v-if="cartlist.length > 0">
        <div class="cart1" v-for="item in cartlist" :key="item._id">
            <input type="checkbox" class="checkbox" v-model="checkedmodel" :value="item._id">
        <img :src="item.product.coverImg" alt="" class="Img">
        <div class="info">
            <p>{{item.product.name}}</p>
            <p class="price">单价：{{item.product.price}}</p>
            <span @click="updatePro(item.product._id, 1)">+</span>
            {{item.quantity}}
            <span @click="item.quantity > 1 && updatePro(item.product._id, -1)">-</span>
          <button @click="del(item._id)" class="btn">删除</button>
          <van-submit-bar
            :price="sumprice * 100"
            button-text="提交订单"  
            @submit="goorder"
            >
      <input type="checkbox" v-model="checked" @click="checkall"/>
      <span>全选</span>
      <van-icon name="delete-o" @click="delpros" class="Delbtn" />
    </van-submit-bar>
        </div>
        </div>
    </div>
    <div v-else>
        <van-empty description="购物车空空如也" />
    </div>
</div>
</template>
<script>
import HeaderCart from "../../components/HeaderCart.vue"
import {reqShowcart} from "../../api/reqShowcart";
import {reqDelcart,reqDelcarts} from "../../api/reqDelcart";
import {addtocart} from "../../api/addcartnum";
import { Toast } from "vant";
import {reqshowAddress,reqSubmitorder} from "../../api/reqshowaddress";
export default {
    data() {
        return {
            checked:false,
            cartlist:[],
            checkedmodel:[],
            sumprice:0,
            addresslist:[],
        };
    },
    computed: {},
    watch: {
        checkedmodel(){
            // 选中列表发生改变则重新计算总价
            this.sumprice = 0;
            // 若选中列表的长度与购物车列表的长度相等则全选按钮点亮,否则不亮
            if(this.checkedmodel.length == this.cartlist.length){
                this.checked = true;
            }else{
                this.checked = false;
            }
            // 计算总价
            for(let i = 0;i < this.checkedmodel.length;i++){
                for(let j = 0;j < this.cartlist.length;j++){
                    if(this.checkedmodel[i] == this.cartlist[j]._id){
                        this.sumprice += this.cartlist[j].product.price * this.cartlist[j].quantity;
                    }
                }
            }
        },
        // 当购物车为空时，全选按钮不亮
        cartlist(){
            if(this.cartlist.length == 0){
                this.checked = false;
                this.sumprice = 0;
            }
        },
    },
    methods: {
        // 初始化购物车
        async initcart(){
            const result = await reqShowcart();
            console.log(result);
            this.cartlist = result;
        },
        // 全选 全不选
        checkall(){
            if(this.checked){
                this.checkedmodel = [];
            }else{
                this.cartlist.forEach(item => {
                    if(this.checkedmodel.indexOf(item._id) == -1){
                        this.checkedmodel.push(item._id);
                    }
                });
            }
        },
        // 购物车商品数量加减修改
        async updatePro(id, num = 1) {
        const result = await addtocart({
            product: id,
            quantity: num,
        });
        this.cartlist.forEach((data) => {
            if (data.product._id == id) {
            data.quantity = data.quantity + num;
            }
        });
        },
        // 购物车商品删除
        async del(id){
            const result = await reqDelcart(id);
            console.log(result);
            this.initcart();
            this.cartlist.forEach((item,index) => {
                if(item._id == id){
                    this.cartlist.splice(index,1);
                }
            });
            // 若删除的商品处于选中状态，则从选中列表中移除
            this.checkedmodel.forEach((item, index) => {
                if (item == id) {
                this.checkedmodel.splice(index, 1);
                }
            });
            if (this.checkedmodel.length == this.cartlist.length) {
                this.checked = true;
            } else {
                this.checked = false;
            }
        },
        // 购物车批量删除
        async delpros(){
            const result = await reqDelcarts(this.checkedmodel);
            console.log(result);
            this.initcart();
        },
        goback(){
            this.$router.back();
        },
        gohome(){
            this.$router.push("/home");
        },
        // 获得所有收货地址
        async initaddress(){
        const result = await reqshowAddress();
        console.log(result);
    
        this.addresslist = result.addresses;
        // 获取默认地址
        this.addresslist.forEach(item => {
            if(item.isDefault){
                this.$store.state.address.receiver = item.receiver;
                this.$store.state.address.regions = item.regions;
                this.$store.state.address.address = item.address;
            }
        })
    },
    //   提交订单
        async goorder(){
            // 选择默认地址
            const receiver = this.$store.state.address.receiver;
            const regions = this.$store.state.address.regions;
            const address = this.$store.state.address.address;
            var goods = [];
            // 获取选中的需要购买的商品
            for(let i = 0;i < this.checkedmodel.length;i++){
                for(let j = 0;j < this.cartlist.length;j++){
                    if(this.checkedmodel[i] == this.cartlist[j]._id){
                        goods.push({
                                quantity:this.cartlist[j].quantity,
                                product:this.cartlist[j].product._id,
                                price:this.cartlist[j].product.price
                            });
                    }
                }
            }
            if(goods.length>0){
                if(receiver && regions && address){
                    const result = await reqSubmitorder({
                        receiver:receiver,
                        regions:regions,
                        address:address,
                        orderDetails:goods,
                    }); 
                    console.log(result);
                    this.$router.push("/order");
                }else{
                    this.$router.push("/address");
                }
            }else{
                Toast('请选择商品后提交订单');
            }
    },
    },
    created() {
        this.initcart();
        this.initaddress();
    },
    mounted() {},
    components: {
        HeaderCart
    },
};
</script>
<style scoped>
.cart-list {
  padding-bottom: 50px;
}
.cart1 {
  display: flex;
  height: 120px;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 15px;
}
.checkbox {
  width: 20px;
  height: 20px;
}
.Img {
  width: 80px;
  height: 80px;
}
.info {
  flex: 1;
  padding-left: 10px;
}
.btn{
    margin-left: 20px;
}
.price{
    color:red;
}
.content {
    padding: 16px;
    border: 1px solid #ccc;
  }
.Delbtn{
    margin-left: 20px;
    font-size: 20px;
}
</style>